<?php

namespace App\Http\Controllers\Home;

use App\Model\Visit;
use App\Model\WineProduct;
use App\Model\WineQrcodeRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DrinkController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        $query = (new WineProduct())->where('has_sku','>',0);

        if ($request->has('category_id')){
            $query->where('category_id','=',$request->input('category_id',0));
            //$query = $query->whereRaw('`id` in (select product_id from `product_category_relations` where  category_id='.$category_id.')');
        }

        if ($request->exists('type')) {
            $type = $request->input('type');
            if ($type == "hot") {
                $query = $query->where('is_hot','=',1);
            }elseif ($type=="recom"){
                $query = $query->where('is_recom','=',1);
            }
        }

        $bool_dev_user = false;
        if (in_array($this->loginUserId(),explode(',',env('DEV_USER_ID',0)))){
            $bool_dev_user = true;
        }

        $dev_product_ids = explode(',',env('DEV_PRODUCT_ID',0));

        if (!$bool_dev_user && count($dev_product_ids)>0){
            $query = $query->whereNotIn('id',$dev_product_ids);
        }

        $items = $query->where('online','=',"yes")
            ->orderBy('weight','desc')
            ->orderBy('created_at','desc')
            ->with(['userWantDrink','sku'])
            ->select('id','name','chname','banner','order_count')
            ->paginate(16);


        return $this->success($items);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function show($id)
    {
        $item = WineProduct::find($id);
        if($item) {
            $this->visit($id,2,$item);

            $item->showDetail();

            return $this->success($item);
        }

        return $this->notFond();


    }

    //从二维码中获取商品
    public function getProductFromQrCode(Request $request)
    {
        $code = $request->input('code');
        $WQR  = WineQrcodeRecord::findByCode($code);
        if ($WQR) {
            if($wineProduct = WineProduct::find($WQR->product_id)){

                $wineProduct->showDetail();

                $this->visit($wineProduct->id,2,$wineProduct,1);

                return $this->respond(['status'=>'success','code'=>200,'qrcode'=>$code,'data'=>[$wineProduct]]);
            }
        }

        return $this->notFond();
    }

    public function category()
    {
        $items = DB::table('product_categories')->whereNull('deleted_at')
            ->select('id','name','icon')
            ->orderBy('sort','asc')->get();
        return $this->success($items);
    }
}
